package com.bestcem.xm.om.grpc.service;

import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ErrorCodeEnum;
import com.bestcem.xm.om.constant.CommonConstant;
import com.bestcem.xm.om.entity.OmUserOperateLog;
import com.bestcem.xm.om.grpc.service.converter.OperateLogConverter;
import com.bestcem.xm.om.grpc.v1.services.CreateOperateLogRequest;
import com.bestcem.xm.om.grpc.v1.services.CreateOperateLogResponse;
import com.bestcem.xm.om.grpc.v1.services.OperateLogServiceGrpc;
import com.bestcem.xm.om.service.OmUserOperateLogService;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;

import javax.annotation.Resource;

/**
 * 查询统计数据
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/1/11 11:11
 */
@Slf4j
@GrpcService
public class OmOperateLogGrpcService extends OperateLogServiceGrpc.OperateLogServiceImplBase {
    /**
     * 机构统计服务
     */
    @Resource
    private OmUserOperateLogService omUserOperateLogService;

    @Override
    public void createOperateLog(CreateOperateLogRequest request,
                                 StreamObserver<CreateOperateLogResponse> responseObserver) {
        OmUserOperateLog userOperateLog = OperateLogConverter.requestToParam(request);

        // 获取统计数据
        ServiceResult<String> serviceResult = omUserOperateLogService.save(userOperateLog);

        CreateOperateLogResponse.Builder builder = CreateOperateLogResponse.newBuilder();
        // 返回数据
        if (serviceResult.isSuccess()) {
            builder.setId(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());
        } else {
            String errMsg = String.format(CommonConstant.ERROR_MSG_FORMATTER, ErrorCodeEnum.SYSTEM_ERROR.getMsg(), serviceResult.getMsg());
            builder.setStatus(RpcStatusResult.error(errMsg));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
